<template>
	<div class="app-card" :class="{ featured: isFeatured }">
		<!-- 卡片主体 -->
		<div class="card-main" @click="handleViewChat">
			<!-- 应用封面区域 -->
			<div class="app-cover-container">
				<img :src="app.cover || logoImg" alt="应用封面" class="app-cover" />
				<!-- 悬浮操作按钮 -->
				<div class="cover-overlay">
					<div class="overlay-actions">
						<a-button type="primary" size="small" @click.stop="handleViewChat" class="action-btn"> 查看对话 </a-button>
						<a-button
							v-if="app.deployKey"
							@click.stop="handleViewDeployedApp"
							size="small"
							class="action-btn secondary"
						>
							查看作品
						</a-button>
					</div>
				</div>
			</div>

			<!-- 应用信息区域 -->
			<div class="app-info">
				<div class="app-header-info">
					<div class="app-icon">
						<UserAvatar :user="displayUser" :size="32" />
					</div>
					<div class="app-details">
						<div class="title-row">
							<h3 class="app-title">{{ app.appName || '未命名应用' }}</h3>
							<div class="status-tags">
								<!-- 精选标签 -->
								<div class="tag featured-tag" v-if="isFeatured">
									<span>精选</span>
								</div>
								<!-- 部署状态标签 -->
								<div class="tag deploy-tag success" v-if="deployStatus === DEPLOY_STATUS.DEPLOYED">
									<span>已部署</span>
								</div>
								<div class="tag deploy-tag processing" v-else-if="deployStatus === DEPLOY_STATUS.DEPLOYING">
									<span>部署中</span>
								</div>
								<div class="tag deploy-tag default" v-else>
									<span>未部署</span>
								</div>
								<!-- 生成状态标签 -->
								<div class="tag generate-tag" v-if="showGenerateStatus">
									<div class="tag-content success" v-if="generateStatus === GENERATE_STATUS.COMPLETED">
										<span>生成成功</span>
									</div>
									<div class="tag-content processing" v-else-if="generateStatus === GENERATE_STATUS.GENERATING">
										<span>生成中</span>
									</div>
									<div class="tag-content error" v-else-if="generateStatus === GENERATE_STATUS.FAILED">
										<span>生成失败</span>
									</div>
									<div class="tag-content warning" v-else-if="generateStatus === GENERATE_STATUS.INTERRUPTED">
										<span>生成中断</span>
									</div>
									<div class="tag-content default" v-else>
										<span>未生成</span>
									</div>
								</div>
							</div>
						</div>
						<div class="app-meta">
							<div class="meta-left">
								<span class="app-author">{{ displayUser?.userName || (showOwnerInfo ? '我' : '匿名') }}</span>
								<span class="app-date">{{ formatTime(app.createTime) }}</span>
							</div>
							<div class="meta-right" v-if="app.codeGenType">
								<a-tag :color="getCodeGenTypeColor(app.codeGenType)" class="code-gen-type-tag" size="small">
									{{ getCodeGenTypeText(app.codeGenType) }}
								</a-tag>
							</div>
						</div>
					</div>
					<!-- 更多操作菜单 -->
					<div class="more-actions" v-if="showActions" @click.stop>
						<a-dropdown :trigger="['click']" placement="bottomRight">
							<a-button type="text" size="small" class="more-btn">
								<template #icon>
									<MoreOutlined />
								</template>
							</a-button>
							<template #overlay>
								<a-menu>
									<a-menu-item @click.stop="handleEdit" v-if="canEdit">
										<EditOutlined />
										编辑
									</a-menu-item>
									<a-menu-item @click.stop="handleUndeploy" v-if="canUndeploy" danger>
										<CloudDownloadOutlined />
										下线应用
									</a-menu-item>
									<a-menu-divider v-if="canEdit || canUndeploy" />
									<a-menu-item @click.stop="handleDelete" danger v-if="canDelete">
										<DeleteOutlined />
										删除
									</a-menu-item>
								</a-menu>
							</template>
						</a-dropdown>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { MoreOutlined, EditOutlined, DeleteOutlined, CloudDownloadOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import logoImg from '@/assets/logo.png'
import { UserAvatar } from '@/components/common'
import { undeployApplication } from '@/services/appExperienceService'
import { useAppStatusTracker } from '@/utils/AppStatusTracker'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { useGenerationStore } from '@/stores/useGenerationStore'
import { DEPLOY_STATUS, GENERATE_STATUS } from '@/constants/appStatus'
import { getCodeGenTypeText, getCodeGenTypeColor } from '@/constants/codeGenType'
import { useAppStatus, computeDeployStatus } from '@/composables/useAppStatus'
import { getDeployUrl } from '@/config/env'

// Props 定义
interface Props {
	app: API.AppVO
	isFeatured?: boolean
	showOwnerInfo?: boolean
	showActions?: boolean
	canEdit?: boolean
	canDelete?: boolean
	showGenerateStatus?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	isFeatured: false,
	showOwnerInfo: false,
	showActions: true,
	canEdit: true,
	canDelete: true,
	showGenerateStatus: false,
})

// Emits 定义
const emit = defineEmits<{
	'view-chat': [appId: string | number]
	edit: [appId: string | number]
	delete: [appId: string | number, callback?: (success: boolean) => void]
	undeploy: [appId: string | number]
}>()

const loginUserStore = useLoginUserStore()
const generationStore = useGenerationStore()

// 添加删除加载状态
const deleting = ref(false)

// 生成状态检查
const generating = computed(() => generationStore.hasActiveGeneration())

// 使用统一的状态管理
const appStatus = props.app.id ? useAppStatus(props.app.id) : null

// 状态追踪
const { startTracking, stopTracking, destroyTracker } = useAppStatusTracker(props.app.id || '')
const generateStatus = ref<number | null>(null)

// 计算显示的用户信息
const displayUser = computed(() => props.app.user)

// 计算部署状态（优先使用状态管理，fallback到兼容函数）
const deployStatus = computed(() => {
	// 确保状态管理被初始化
	if (appStatus) {
		appStatus.ensureStatusInitialized(props.app)
		const statusInfo = appStatus.deployInfo.value
		if (statusInfo) {
			return statusInfo.status
		}
	}

	// 兼容性fallback
	const computed_status = computeDeployStatus(props.app)
	return computed_status
})

// 是否可以下线应用（只有已部署的应用才能下线，且用户是应用创建者）
const canUndeploy = computed(() => {
	const isOwner = props.app.userId === loginUserStore.loginUser?.id
	const isDeployed = deployStatus.value === DEPLOY_STATUS.DEPLOYED
	return isOwner && isDeployed && props.showActions
})

// 组件挂载时开始状态追踪（如果需要且用户已登录）
onMounted(() => {
	// 初始化状态管理
	if (appStatus && props.app) {
		appStatus.updateFromAppVO(props.app)
	}

	// 检查是否需要状态追踪的条件：
	// 1. 需要显示生成状态
	// 2. 用户已登录
	// 3. 应用ID存在
	// 4. 是用户自己的应用（只追踪自己的应用状态）
	const isOwnerApp = props.app.userId === loginUserStore.loginUser?.id
	const shouldTrack =
		props.showGenerateStatus && props.app.id && loginUserStore.loginUser?.id && isOwnerApp && !props.isFeatured // 精选应用不需要状态追踪

	if (shouldTrack) {
		// 先获取一次状态，如果已经是终态就不启动轮询
		import('@/services/appExperienceService').then(({ getApplicationStatus, convertStatusStringToNumber }) => {
			getApplicationStatus(props.app.id!)
				.then((res) => {
					if (res.data.code === 0 && res.data.data) {
						const numericStatus = convertStatusStringToNumber(res.data.data)
						generateStatus.value = numericStatus

						// 只有在生成中的状态才启动轮询
						if (numericStatus === 1) {
							// GENERATING 状态
							startTracking({
								onStatusChange: (status: string) => {
									generateStatus.value = parseInt(status)
								},
								onError: (error) => {
									console.error('状态追踪失败:', error)
								},
							})
						}
					}
				})
				.catch((error) => {
					console.error('获取初始状态失败:', error)
				})
		})
	}
})

// 监听用户登录状态变化
watch(
	() => loginUserStore.loginUser?.id,
	(newUserId: string | number | undefined, oldUserId: string | number | undefined) => {
		if (props.showGenerateStatus && props.app.id) {
			if (newUserId && !oldUserId) {
				// 用户登录了，但只对自己的应用且在生成中的状态启动追踪
				const isOwnerApp = props.app.userId === newUserId
				if (isOwnerApp && !props.isFeatured) {
					// 检查状态后再决定是否启动追踪
					import('@/services/appExperienceService').then(({ getApplicationStatus, convertStatusStringToNumber }) => {
						getApplicationStatus(props.app.id!)
							.then((res) => {
								if (res.data.code === 0 && res.data.data) {
									const numericStatus = convertStatusStringToNumber(res.data.data)
									generateStatus.value = numericStatus

									if (numericStatus === 1) {
										// 只有正在生成中才启动追踪
										startTracking({
											onStatusChange: (status: string) => {
												generateStatus.value = parseInt(status)
											},
											onError: (error) => {
												console.error('状态追踪失败:', error)
											},
										})
									}
								}
							})
							.catch((error) => {
								console.error('获取状态失败:', error)
							})
					})
				}
			} else if (!newUserId && oldUserId) {
				// 用户退出登录，停止状态追踪
				stopTracking()
			}
		}
	}
)

// 组件卸载时销毁追踪器
onUnmounted(() => {
	destroyTracker()
})

// 处理事件
const handleViewChat = () => {
	emit('view-chat', props.app.id!)
}

const handleViewDeployedApp = () => {
	// 直接访问部署地址 {VITE_APP_BASE_URL}/{deployKey}
	if (props.app.deployKey) {
		const deployUrl = getDeployUrl(props.app.deployKey, props.app.userId)
		window.open(deployUrl, '_blank')
	} else {
		console.warn('应用缺少部署密钥')
	}
}

const handleEdit = () => {
	if (generating.value) {
		message.warning('AI 正在生成中，请等待完成后再进行编辑操作')
		return
	}
	emit('edit', props.app.id!)
}

const handleDelete = async () => {
	// 如果正在删除，直接返回
	if (deleting.value) return
	
	// 如果正在生成，先中断SSE流式传输
	if (generating.value && props.app.id) {
		try {
			// 导入中断生成任务的API
			const { interruptGenerationTask } = await import('@/services/appExperienceService')
			await interruptGenerationTask(props.app.id)
			message.info('已中断当前生成任务')
		} catch (error) {
			console.warn('中断生成任务失败:', error)
			// 即使中断失败也继续删除流程
		}
	}

	Modal.confirm({
		title: '确认删除应用',
		content: `确定要删除应用 "${props.app.appName || '未命名应用'}" 吗？删除后无法恢复。`,
		okText: '确认删除',
		cancelText: '取消',
		okType: 'danger',
		onOk: () => {
			// 设置删除状态为true
			deleting.value = true
			
			// 传递回调函数来处理删除完成后的状态重置
			emit('delete', props.app.id!, (success: boolean) => {
				deleting.value = false
			})
		},
	})
}

// 下线应用
const handleUndeploy = () => {
	if (!props.app.id) return

	if (generating.value) {
		message.warning('AI 正在生成中，请等待完成后再进行下线操作')
		return
	}

	Modal.confirm({
		title: '确认下线应用',
		content: '下线后用户将无法访问此应用，确定要下线吗？',
		okText: '确认下线',
		cancelText: '取消',
		okType: 'danger',
		onOk: async () => {
			try {
				const res = await undeployApplication(props.app.id!)
				if (res.data.code === 0) {
					message.success('应用已下线')
					// 更新状态管理
					if (appStatus) {
						appStatus.updateDeployStatus(DEPLOY_STATUS.NOT_DEPLOYED)
					}
					emit('undeploy', props.app.id!)
				} else {
					message.error('下线失败：' + (res.data.message || '未知错误'))
				}
			} catch (error) {
				console.error('下线应用失败:', error)
				message.error('下线失败，请稍后重试')
			}
		},
	})
}

// 格式化时间
const formatTime = (time: string | undefined) => {
	if (!time) return ''
	return dayjs(time).format('YYYY-MM-DD')
}
</script>

<style scoped lang="scss">
// CSS变量定义
:root {
	--card-bg: #ffffff;
	--card-border: #f0f0f0;
	--card-radius: 16px;
	--card-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	--card-shadow-hover: 0 20px 40px rgba(0, 0, 0, 0.1);
	--primary-color: #1890ff;
	--success-color: #52c41a;
	--text-primary: #262626;
	--text-secondary: #595959;
	--text-tertiary: #8c8c8c;
}

.app-card {
	background: var(--card-bg);
	border-radius: var(--card-radius);
	overflow: hidden;
	transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
	border: 1px solid var(--card-border);
	position: relative;
	box-shadow: var(--card-shadow);

	&:hover {
		transform: translateY(-8px);
		box-shadow: var(--card-shadow-hover);
		border-color: #e6f4ff;

		.app-cover-container .cover-overlay {
			opacity: 1 !important;
		}

		.app-cover {
			transform: scale(1.05);
		}

		.app-info .app-header-info {
			.app-title {
				color: var(--primary-color);
			}

			.more-actions {
				opacity: 1;
			}
		}

		.category-badge {
			transform: translateY(-2px) scale(1.05);
			box-shadow: 0 4px 12px rgba(82, 196, 26, 0.4);
		}

		.status-badges .status-badge {
			transform: translateY(-1px);
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
		}
	}

	&.featured {
		border: 1px solid #d9f7be;
		background: linear-gradient(145deg, #ffffff 0%, #f6ffed 100%);
	}

	.card-main {
		cursor: pointer;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.app-cover-container {
		position: relative;
		height: 200px;
		background: #fafafa;
		overflow: hidden;

		.app-cover {
			width: 100%;
			height: 100%;
			object-fit: cover;
			transition: transform 0.3s ease;
		}

		.cover-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.6);
			display: flex;
			align-items: center;
			justify-content: center;
			opacity: 0;
			transition: opacity 0.3s ease;
			backdrop-filter: blur(2px);
			z-index: 10; /* 确保悬浮层在最上层 */
			pointer-events: none; /* 当不可见时不接收事件 */

			/* 临时调试：取消注释下面这行来测试按钮是否存在 */
			/* opacity: 1 !important; */

			.overlay-actions {
				display: flex;
				gap: 12px;
				pointer-events: auto; /* 恢复按钮事件 */

				.action-btn {
					height: 36px;
					border-radius: 18px;
					font-weight: 500;
					font-size: 14px;
					backdrop-filter: blur(10px);
					border: none;
					box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
					position: relative;
					z-index: 20;

					&.secondary {
						background: rgba(255, 255, 255, 0.9);
						color: #1890ff;

						&:hover {
							background: rgba(255, 255, 255, 1);
							transform: translateY(-1px);
						}
					}

					&:hover {
						transform: translateY(-1px);
						box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
					}
				}
			}
		}

		// 现代化类别标签 - 参考图片2
		.category-badge {
			position: absolute;
			top: 12px;
			left: 12px;
			background: linear-gradient(135deg, #52c41a, #73d13d);
			color: white;
			padding: 4px 12px;
			border-radius: 20px;
			font-size: 11px;
			font-weight: 600;
			letter-spacing: 0.5px;
			box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
			backdrop-filter: blur(10px);
			transform: translateY(0);
			transition: all 0.3s ease;

			span {
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
			}

			&::before {
				content: '✨';
				margin-right: 4px;
				font-size: 10px;
			}
		}

		// 状态标识
		.status-badges {
			position: absolute;
			top: 12px;
			right: 12px;

			.status-badge {
				padding: 4px 10px;
				border-radius: 16px;
				font-size: 11px;
				font-weight: 500;
				backdrop-filter: blur(10px);
				box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);

				&.success {
					background: rgba(82, 196, 26, 0.9);
					color: white;
					box-shadow: 0 2px 6px rgba(82, 196, 26, 0.25);
				}

				&.processing {
					background: rgba(24, 144, 255, 0.9);
					color: white;
					box-shadow: 0 2px 6px rgba(24, 144, 255, 0.25);
				}
			}
		}
	}

	.app-info {
		padding: 12px;
		flex: 1;
		background: white;
		border-top: 1px solid #f5f5f5;

		.app-header-info {
			display: flex;
			align-items: flex-start;
			gap: 5px;
			position: relative;

			.app-icon {
				flex-shrink: 0;
				margin-top: 2px;
			}

			.app-details {
				flex: 1;
				min-width: 0;
				// 为more-actions留出空间，避免重叠
				padding-right: 35px;

				.title-row {
					display: flex;
					justify-content: space-between;
					align-items: flex-start;
					margin-bottom: 6px;
					gap: 0px;

					.app-title {
						font-size: 16px;
						font-weight: 600;
						color: var(--text-primary);
						margin: 0;
						line-height: 1.4;
						flex: 1;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						line-clamp: 1;
						-webkit-box-orient: vertical;
						overflow: hidden;
						transition: color 0.2s ease;
					}

					.status-tags {
						display: flex;
						gap: 4px;
						flex-shrink: 0;
						flex-wrap: wrap;
						justify-content: flex-end;

						.tag {
							font-size: 10px;
							font-weight: 500;
							padding: 2px 6px;
							border-radius: 8px;
							white-space: nowrap;
							line-height: 1.2;

							&.featured-tag {
								background: linear-gradient(135deg, #52c41a, #73d13d);
								color: white;
								box-shadow: 0 1px 3px rgba(82, 196, 26, 0.3);
							}

							&.deploy-tag {
								&.success {
									background: rgba(82, 196, 26, 0.1);
									color: #52c41a;
									border: 1px solid rgba(82, 196, 26, 0.3);
								}

								&.processing {
									background: rgba(24, 144, 255, 0.1);
									color: #1890ff;
									border: 1px solid rgba(24, 144, 255, 0.3);
								}

								&.default {
									background: rgba(140, 140, 140, 0.1);
									color: #8c8c8c;
									border: 1px solid rgba(140, 140, 140, 0.3);
								}
							}

							&.generate-tag {
								.tag-content {
									&.success {
										background: rgba(82, 196, 26, 0.1);
										color: #52c41a;
										border: 1px solid rgba(82, 196, 26, 0.3);
										padding: 2px;
										border-radius: 8px;
									}

									&.processing {
										background: rgba(24, 144, 255, 0.1);
										color: #1890ff;
										border: 1px solid rgba(24, 144, 255, 0.3);
										padding: 2px 6px;
										border-radius: 8px;
									}

									&.error {
										background: rgba(255, 77, 79, 0.1);
										color: #ff4d4f;
										border: 1px solid rgba(255, 77, 79, 0.3);
										padding: 2px 6px;
										border-radius: 8px;
									}

									&.warning {
										background: rgba(250, 173, 20, 0.1);
										color: #faad14;
										border: 1px solid rgba(250, 173, 20, 0.3);
										padding: 2px 6px;
										border-radius: 8px;
									}

									&.default {
										background: rgba(140, 140, 140, 0.1);
										color: #8c8c8c;
										border: 1px solid rgba(140, 140, 140, 0.3);
										padding: 2px 6px;
										border-radius: 8px;
									}
								}
							}
						}
					}
				}

				.app-meta {
					display: flex;
					align-items: center;
					justify-content: space-between;
					gap: 8px;
					font-size: 13px;
					min-height: 20px;

					.meta-left {
						display: flex;
						align-items: center;
						gap: 12px;
						flex: 1;
						min-width: 0; // 允许内容缩小

						.app-author {
							color: var(--text-secondary);
							font-weight: 500;
							white-space: nowrap;
						}

						.app-date {
							color: var(--text-tertiary);
							position: relative;
							white-space: nowrap;

							&::before {
								content: '•';
								margin-right: 8px;
								color: #d9d9d9;
							}
						}
					}

					.meta-right {
						flex-shrink: 0;

						.code-gen-type-tag {
							font-size: 11px !important;
							padding: 1px 6px !important;
							border-radius: 10px !important;
							line-height: 1.4 !important;
							margin: 0 !important;
						}
					}
				}
			}

			.more-actions {
				position: absolute;
				top: 0;
				right: 0;
				flex-shrink: 0;
				opacity: 0;
				transition: opacity 0.2s ease;

				.more-btn {
					width: 28px;
					height: 28px;
					border-radius: 6px;
					display: flex;
					align-items: center;
					justify-content: center;
					color: var(--text-tertiary);
					border: 1px solid transparent;

					&:hover {
						background: #f5f5f5;
						color: var(--text-primary);
						border-color: #d9d9d9;
					}
				}
			}
		}
	}
}

// 动画效果
@keyframes gentle-pulse {
	0%,
	100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.02);
	}
}

@keyframes fade-in-up {
	from {
		opacity: 0;
		transform: translateY(20px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.app-card {
	animation: fade-in-up 0.6s ease-out;
}

// 响应式设计
@media (max-width: 768px) {
	.app-card {
		.app-cover-container {
			height: 160px;

			.cover-overlay .overlay-actions {
				flex-direction: column;
				gap: 8px;

				.action-btn {
					height: 32px;
					font-size: 13px;
				}
			}

			.category-badge {
				font-size: 10px;
				padding: 3px 10px;
			}
		}

		.app-info {
			padding: 12px;

			.app-header-info {
				.app-details {
					.app-title {
						font-size: 15px;
					}

					.app-meta {
						font-size: 12px;
						gap: 6px;

						.meta-right {
							.code-gen-type-tag {
								font-size: 10px !important;
								padding: 1px 4px !important;
							}
						}
					}
				}
			}
		}
	}
}
</style>
